package com.bjpowernode.web.config;

import com.bjpowernode.web.interceptor.TokenInterceptor;
import org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Resource;

/**
 * @author 麦翔盛
 * @ClassName: WebMvcConfi
 * @Package: com.bjpowernode.web.config
 * @description: spring mvc全局配置
 * @date 2022/5/21 23:23
 */

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        TokenInterceptor tokenInterceptor = new TokenInterceptor();
        tokenInterceptor.setRedisTemplate(stringRedisTemplate);

        //设置拦截器拦截路径
        String[] addPaths = {"/v1/user/realname"};

        //添加拦截器和拦截路径
        registry.addInterceptor(tokenInterceptor).addPathPatterns(addPaths);
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")  //拦截路径
                .allowedOriginPatterns("*")   //可以跨域的域名，eg:http://localhost:8080
                .allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS")
                .allowCredentials(true)    //是否支持发送cookie
                .maxAge(3600)              //预检时间
                .allowedHeaders("*");      //请求头带什么参数
    }
}
